<template>
  <el-dialog title="设置角色" :visible.sync="dialogVisible" width="15%" :close-on-click-modal="false">
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="100px">
      <el-checkbox-group v-model="model.roleNames">
        <el-checkbox v-for="item in assignableRoles" :key="item.name" :label="item.name" class="item">{{ item.extraProperties.DisplayName }}</el-checkbox>
      </el-checkbox-group>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getAssignableRoles, getUserRoles, setUserRoles } from "@/api/identity/user";

export default {
  data() {
    return {
      dialogVisible: false,
      isSubmitLoading: false,
      assignableRoles: [],
      userRoles: [],
      userId: undefined,
      model: {
        roleNames: []
      },
      modelRules: {
        roleNames: [{ required: true, trigger: "blur", message: "请输入至少选择一个角色" }]
      }
    };
  },
  methods: {
    show(id) {
      this.resetModal();
      this.isSubmitLoading = false;
      this.userId = id;

      getAssignableRoles().then(roles => {
        this.assignableRoles = roles.items;
        getUserRoles(id).then(userRoles => {
          this.userRoles = userRoles.items;
          this.model.roleNames = userRoles.items.map(item => item.name);
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].clearValidate();
          });
        });
      });
    },
    resetModal() {
      this.model = {
        roleNames: []
      };
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.isSubmitLoading = false;
          this.$message({ message: this.$t("formIsNotValidMessage"), type: "warning" });
          return;
        }
        setUserRoles(this.userId, this.model)
          .then(() => {
            this.$message({ message: "设置成功", type: "success" });
            this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
            this.close();
          })
          .finally(() => {
            this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          });
      });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    }
  }
};
</script>

<style scope>
.item {
  display: block;
  margin-bottom: 10px;
}
</style>

